<template>
    <div class="signature">
        <canvas
            class="my-canvas"
            canvas-id="myCanvas"
            :disable-scroll="true"
            :style="{ height: height, width: width }"
            @touchstart="touchstart"
            @touchmove="touchmove"
            @touchend="touchend"
        />
        <view class="water-mark"> 签名区 </view>

        <!--<div style="width: 0; height: 0; overflow: hidden">-->
        <!--<canvas-->
        <!--class="rotate-canvas"-->
        <!--canvas-id="rotateCanvas"-->
        <!--:disable-scroll="true"-->
        <!--:style="{ height: rotateHeight + 'rpx', width: rotateWidth + 'rpx' }"-->
        <!--/>-->
        <!--</div>-->
    </div>
</template>

<script>
import { baseUrl } from '@/utils/config';
export default {
    name: 'Signature',
    props: {
        height: {
            type: String,
            default: '100vh',
        },
        width: {
            type: String,
            default: '100%',
        },
    },
    data() {
        return {
            ctx: {}, // 绘图图像
            points: [], // 路径点集合
            tempFilePath: null,
            // 当前签名是否为空
            isEmpty: true,
            // rotateWidth: 0,
            // rotateHeight: 0,
        };
    },
    created() {
        // 创建绘图对象
        this.ctx = uni.createCanvasContext('myCanvas', this);
        // 设置画笔样式
        this.ctx.lineWidth = 4;
        this.ctx.lineCap = 'round';
        this.ctx.lineJoin = 'round';
    },
    methods: {
        // 触摸开始，获取到起点
        touchstart(e) {
            const startX = e.changedTouches[0].x;
            const startY = e.changedTouches[0].y;
            const startPoint = {
                X: startX,
                Y: startY,
            };
            this.points.push(startPoint);
            // 每次触摸开始，开启新的路径
            this.ctx.beginPath();
        },
        // 触摸移动，获取到路径点
        touchmove(e) {
            const moveX = e.changedTouches[0].x;
            const moveY = e.changedTouches[0].y;
            const movePoint = {
                X: moveX,
                Y: moveY,
            };
            this.points.push(movePoint); // 存点
            const len = this.points.length;
            if (len >= 2) {
                this.draw(); // 绘制路径
            }
        },
        // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
        touchend() {
            this.points = [];
            this.isEmpty = false;
            this.finish();
        },
        /*
         * 绘制笔迹
         * 1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
         * 2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
         * 3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
         */
        draw() {
            const point1 = this.points[0];
            const point2 = this.points[1];
            this.points.shift();
            this.ctx.moveTo(point1.X, point1.Y);
            this.ctx.lineTo(point2.X, point2.Y);
            this.ctx.stroke();
            this.ctx.draw(true);
        },
        // 清空画布
        clear() {
            this.isEmpty = true;
            uni.getSystemInfo({
                success: res => {
                    const canvasWidth = res.windowWidth;
                    const canvasHeight = res.windowHeight;
                    this.ctx.clearRect(0, 0, canvasWidth, canvasHeight);
                    this.ctx.draw(true);
                },
            });
        },
        // 完成绘画并保存到本地
        finish() {
            let that = this;
            uni.canvasToTempFilePath(
                {
                    canvasId: 'myCanvas',
                    fileType: 'png',
                    success: function (res) {
                        console.log(res.tempFilePath);
                        that.tempFilePath = res.tempFilePath;
                        that.$emit('onChange');
                    },
                    fail: function (err) {
                        uni.showToast({
                            title: '绘制失败',
                            icon: 'none',
                        });
                    },
                },
                this,
            );
        },
        // 上传
        upload() {
            if (this.isEmpty) {
                this.$emit('showEmptyHint');
                return;
            }
            uni.showLoading();
            this.uploadSignatureImage(this.tempFilePath);
            // this.rotateBase64Img(this.tempFilePath, 270);
        },
        rotateBase64Img(src, edg) {
            let that = this;
            uni.getImageInfo({
                src,
                success: res => {
                    let ctx = uni.createCanvasContext('rotateCanvas', that);
                    let rate = res.height / res.width;
                    this.rotateWidth = 300 * rate;
                    this.rotateHeight = 300;
                    // ctx.translate(this.rotateHeight / 2, this.rotateWidth / 2);
                    ctx.rotate((edg * Math.PI) / 180);
                    ctx.drawImage(
                        src,
                        -this.rotateWidth / 2,
                        -this.rotateHeight / 2,
                        this.rotateWidth,
                        this.rotateHeight,
                    );
                    ctx.draw(false, () => {
                        uni.canvasToTempFilePath(
                            {
                                canvasId: 'rotateCanvas',
                                fileType: 'png',
                                success: res => {
                                    console.log('res.tempFilePath');
                                    console.log(res.tempFilePath);
                                    that.tempFilePath = res.tempFilePath;
                                },
                            },
                            that,
                        );
                    });
                },
            });
        },
        uploadSignatureImage(path) {
            let that = this;
            uni.uploadFile({
                header: {
                    Authorization: 'Bearer ' + uni.getStorageSync('token'),
                    'tenant-id': 1,
                },
                url: baseUrl + '/app-api/study-hall/protocol/sign-pic',
                filePath: path,
                name: 'signPic',
                success: res => {
                    let { data } = JSON.parse(res.data);
                    uni.showToast({
                        title: '上传成功',
                        icon: 'none',
                    });
                    that.$emit('onFinish', data);
                },
                fail: error => {
                    uni.showToast({
                        title: '上传失败',
                        icon: 'none',
                    });
                },
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.signature {
    position: relative;
    .my-canvas {
        background-color: #cfcfcf;
        position: relative;
    }
    .rotate-canvas {
        /*display: none;*/
    }
    .water-mark {
        font-size: 88rpx;
        transform: translate(-50%, -50%) rotate(90deg);
        z-index: 1;
        top: 50%;
        left: 50%;
        position: absolute;
        color: rgba(0, 0, 0, 0.3);
        pointer-events: none;
    }
}
</style>
